from flask import Blueprint, jsonify, request
import json
from db import db1
import time
from utils.rediscoon import r
from utils.sendsms import send_message
import random
import re
from utils.jwttoken import myjwt

bp_admin = Blueprint('admin', __name__)


def get_data():
    data = request.data
    if data:
        data = json.loads(data)
    else:
        data = request.form
    return data


@bp_admin.route('/roles', methods=['POST', 'GET'])
def roles():
    if request.method == 'POST':
        data = get_data()
        sql1 = '''select id from roles where name = "%s" ''' % (data['name'])
        res1 = db1.findall(sql1)
        if res1:
            return jsonify({'code': 20010, 'mes': '该角色已存在'})
        else:
            sql = '''insert into roles values(0,"%s")''' % (data['name'])
            db1.update(sql)
            return jsonify({'code': 200})
    elif request.method == 'GET':
        sql1 = '''select * from roles'''
        res1 = db1.findall(sql1)
        sql2 = '''select * from resources'''
        res2 = db1.findall(sql2)
        return jsonify({'code': 200, 'list1': res1, 'list2': res2})


@bp_admin.route('/resources', methods=['POST'])
def resources():
    if request.method == 'POST':
        data = get_data()
        sql1 = '''select id from resources where name = "%s" ''' % (data['name'])
        res1 = db1.findall(sql1)
        if res1:
            return jsonify({'code': 20010, 'mes': '该资源已存在'})
        else:
            sql = '''insert into resources values(0,"%s","%s")''' % (data['name'], data['url'])
            db1.update(sql)
            return jsonify({'code': 200})


@bp_admin.route('/jszy', methods=['POST', 'GET'])
def jszy():
    if request.method == 'POST':
        data = get_data()
        sql = '''delete from role_resources where role_id = %d ''' % (int(data['role_id']))
        db1.update(sql)
        ids = data['ids']
        for i in ids:
            sql = '''insert into role_resources values(0,%d,%d,%d)''' % (int(data['role_id']), i, 1)
            db1.update(sql)
        return jsonify({'code': 200})
    elif request.method == 'GET':
        id = request.args.get('id')

        sql = '''select resources_id from role_resources where role_id = %d ''' % (int(id))
        res = db1.findall(sql)
        list1 = []
        for i in res:
            list1.append(i['resources_id'])
        print(list1)
        return jsonify({'code': 200, 'idlist': list1})


@bp_admin.route('/user', methods=['POST'])
def user():
    if request.method == 'POST':
        data = get_data()
        sql = '''select id from admin_user where name = "%s" ''' % (data['name'])
        res = db1.findall(sql)
        if res:
            return jsonify({'code': 20010, 'mes': '手机号已存在'})
        else:
            sql = '''insert into admin_user values(0,"%s","%s",%d,%d)''' % (
                data['name'], "123", 1, int(data['role_id']))
            db1.update(sql)
            return jsonify({'code': 200})


@bp_admin.route('/send', methods=['GET', 'POST'])
def send():
    if request.method == 'GET':
        mobile = int(request.args.get('mobile'))
        if not re.match('^1[3-9]\d{9}$', str(mobile)):
            return jsonify({'code': 20010, 'ts': '手机号错误'})
        value = r.get_str(mobile)
        if value:
            return jsonify({'code': 10011, 'ts': '验证码已发送，请1分钟后再试'})

        codess = random.randint(100000, 999999)
        flag = send_message(mobile, codess, 1)
        if flag:
            r.set_str(mobile, codess, 60)
            return jsonify({'code': 200})
        else:
            return jsonify({'code': 20012, 'ts': '验证码发送失败'})


@bp_admin.route('/login', methods=['POST'])
def login():
    pass
    if request.method == 'POST':
        # 手机号、验证码发起请求 -》根据手机号去redis中取验证码 -》没取到直接返回
        # redis取出来的验证码，输入的对比 -》对比成功 -》去数据库查询 -》手机号存在 -》生成token返回
        data = get_data()
        value = r.get_str(data['mobile'])
        if not value:
            return jsonify({'code': 20013, 'mes': '验证码不存在'})
        if int(value) == int(data['codes']):

            sql = 'select * from admin_user where name = "%s" ' % (data['mobile'])
            print(sql)
            res = db1.findone(sql)
            if res:
                sql1 = 'select r.* from resources as r inner join role_resources as rr on r.id = rr.resources_id where rr.role_id = %d ' % (
                    int(res['role_id']))
                zylist = db1.findall(sql1)
                stime = time.time()
                token = myjwt.encode_jwt(
                    {'data': {'mobile': res['name'], 'userid': res['id'], 'iat': stime, 'exp': 3600}})
                retoken = myjwt.encode_jwt({'data': {'iat': stime, 'exp': 7200}})
                # print(res)
                # print(zylist)
                # print(token)
                # print(retoken)
                r.del_str(data['mobile'])
                return jsonify({'code': 200, 'token': token, 'retoken': retoken, 'list': res, 'ziyuan': zylist})
            else:
                return jsonify({'code': 20014, 'mes': '用户不存在'})
        else:
            return jsonify({'code': 20015, 'mes': '验证码错误'})


@bp_admin.before_request
def before():
    # 定义一个白名单，把不需要token认证的接口放到列表里
    print(request.path)
    list = ['/admin/send', '/admin/login']
    if request.path not in list:
        try:
            token = request.headers['Token']
        except:
            return jsonify({'code': 20016, 'mes': '无权访问'})
        data = myjwt.decode_jwt(token)
        if data:
            ctime = data['data']['iat']
            exptime = data['data']['exp']
            if int(time.time() - ctime) > exptime:
                return jsonify({'code': 20017, 'mes': 'token已过期'})
        if myjwt.check_jwt(token) == False:
            return jsonify({'code': 20018, 'mes': 'token不正确'})


@bp_admin.route('/retoken', methods=['POST'])
def retoken():
    if request.method == 'POST':
        # 重新生成token
        # 获取retoken
        data = get_data()
        retoken = data['retoken']
        # 解析retoken，是否过期
        flag = myjwt.check_jwt(retoken)
        if flag:
            payload = myjwt.decode_jwt(retoken)
            if payload:
                # 创建时间
                ctime = payload['data']['iat']
                # 设置token过期时间
                exptime = payload['data']['exp']

                if int(time.time() - ctime) > exptime:
                    # token是否过期
                    return jsonify({"code": 401, 'mes': 'token已经过期'})
                else:
                    # 没过期，重新生成token
                    data = {
                        'data': {"username": data['mobile'], "userid": data['userid'], "iat": time.time(), "exp": 3600}}
                    newtoken = myjwt.jwt_en(data)
                    data1 = {'data': {"iat": time.time(), "exp": 7200}}
                    newretoken = myjwt.jwt_en(data1)
                    return jsonify({"code": 200, 'token': newtoken, 'retoken': newretoken})
        return jsonify({"code": 401, 'mes': 'retoken不能使用,请重新登录'})
